import latex2mathml.converter
from docx import Document
from lxml import etree


def latex_to_mathml(latex_str: str) -> str:
    """
    latex 转成 mathml表达式
    :param latex_str: latex字符串
    :return: mathml表达式
    """
    return latex2mathml.converter.convert(latex_str)


xslt = etree.parse(r"./plug/MML2OMML.XSL")
xslt_transform = etree.XSLT(xslt)


def mathml_to_oxml(mathml_str: str):
    """
    mathml表达式 转换成word的oxml
    :param mathml_str: mathml表达式
    :return: word的oxml dom
    """
    mathml_xml = etree.fromstring(mathml_str)
    return xslt_transform(mathml_xml).getroot()


def latex_to_oxml(latex_str: str):
    mathml_str = latex_to_mathml(latex_str)
    return mathml_to_oxml(mathml_str)


if __name__ == '__main__':
    latex_str = r'\frac{\frac{a}{c}}{b}\times d\%'
    # 创建一个新的 Word 文档
    doc = Document()
    # 添加一个段落
    paragraph = doc.add_paragraph()
    # 创建一个 run 对象
    run = paragraph.add_run()
    run._element.append(latex_to_oxml(latex_str))
    # 保存文档
    doc.save('example.docx')